package service;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import entity.Admin;
import entity.Score;
import entity.Student;
import entity.TeacherSubject;
import factory.CommonServiceFactory;
import factory.UserModelFactory;
import mapper.ScoreMapper;
import mapper.StudentMapper;
import mapper.TeacherSubjectMapper;
import model.UserModel;

@Service
public class StudentService {
	private CommonService studentCommonService;
	@Autowired
	private TeacherSubjectMapper teacherSubjectMapper;
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private ScoreMapper scoreMapper;
	private UserModel studentModel;
	public StudentService() {
		studentCommonService = CommonServiceFactory.create(CommonServiceFactory.STUDENT);
	}
	public Student login(Student student,HttpSession session) {
		if(studentCommonService.checkPassword(student.getUsername(), student.getPassword(),studentMapper)) {
			Student tstudent = studentMapper.findByUsername(student.getUsername());
			session.setAttribute("student", tstudent);
			return tstudent;
			
		}else {
			return null;
		}
	}
	
	public ArrayList<Score>  findScoreByStudentAndSubject(HttpSession session,String teacherSubjectId) {
		Student student  = (Student)session.getAttribute("student");
		Score score = new Score();
		score.setStudent(student);
		TeacherSubject teacherSubject = new TeacherSubject();
		teacherSubject.setId(teacherSubjectId);
		score.setTeacherSubject(teacherSubject);
		return  scoreMapper.findByStudentAndSubject(score);
	}
	public Student findById(String id) {
		return studentMapper.findById(id);
	}
	public ArrayList<Student> findAll(HttpSession session){
		Admin admin = (Admin)session.getAttribute("admin");
		if(admin!=null) {
			return studentMapper.findAll();
		}else {
			return null;
		}
	}
	public String add(Student student,HttpSession session) {
		studentModel = UserModelFactory.create(session, student, studentMapper);
		return studentModel.doAdd();
	}
	public String delete(Student student,HttpSession session) {
		studentModel = UserModelFactory.create(session, student, studentMapper);
		return studentModel.doDelete();
	}
	public String alter(Student student,HttpSession session) {
		studentModel = UserModelFactory.create(session, student, studentMapper);
		return studentModel.doAlter();
	}
	public ArrayList<Student> findByClasses(String teacherSubjectId){
		TeacherSubject teacherSubject = teacherSubjectMapper.findById(teacherSubjectId);
		
		return  studentMapper.findByClasses(teacherSubject.getClasses().getId());
	}
	
	public ArrayList<TeacherSubject> findTeacherSubjectByClasses(HttpSession session){
		Student student = (Student)session.getAttribute("student");
		return teacherSubjectMapper.findByClassesId(student.getStudentClass().getId());
	}

}
